var empty = true;
var playlist = "";
var auth = "";

function getUrlArgs()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

/*function replaceVotch() {
	var dH = $(document).height();
	var wH = $(window).height();
	var h;
	if (dH > wH)
		h = dH;
	else
		h = wH - 20;

	var top = h;
	if (top < 600)
		top = 600;
	var left = parseInt($(window).width() / 2);
	if (left < 520)
		left = 520;
	$("#votch").css("top", top + "px").css("left", left + "px");
}
*/
function initMessages() {
	var lang = getUrlArgs() ["lang"];
	if(!lang) {
		lang = $.i18n.browserLang();
	}
	
	$.i18n.properties( {
		name: 'SkippingTricktionary',
		language: lang//,
		//callback : initMessages()
	});
	$("#title").text(m.title);
	$("#byAuthor").text(m.byAuthor);
	$("#m_instruction1").text(m.instruction1);
	$("#m_instruction2").text(m.instruction2);
	$("#m_ask").text(m.ask);
	$("#m_addToPlaylist").text(m.addToPlaylist);
	$("#m_showMore").text(m.showMore);
	$("#m_first").text(m.first);
	$("#m_last").text(m.last);
	$("#m_page").text(m.page);
	$("#m_from").text(m.from);
	//$("#m_type").text(m.type);
	$("#m_level").text(m.level);
	$("#m_clearTags").text(m.clearTags);
	$("#m_searchResults").text(m.searchResults);
	$("#m_playlist").text(m.playlist);
	$("#m_playlistCount").text("0");
	$("#m_postCommentBtn").text(m.postCommentBtn);
	$("#m_aboutOgo").text(m.aboutOgo);
	
	$.i18n.properties( {
		name: 'Tags',
		language: lang,
		mode: 'map'//,
		//callback : initMessages()
	});
	// init tags
	$.each($(".tagMsg"), function() {
		$(this).text($.i18n.prop(this.id));
	});
}

function initTags() {
	initMessages();
	initAll();
}

function initAll() {
//	$(window).resize(function() {
//		replaceVotch();
//	});
//	replaceVotch();
//	$("#votch").css("display", "block");

	$(".tag").attr("checked", "false").addClass("notselected").click(
			function() {
				checkPlaylist(false);

				if ($(this).attr("checked") == "false") {
					$(this).removeClass("notselected").addClass("selected")
							.attr("checked", "true");
				} else {
					$(this).removeClass("selected").addClass("notselected")
							.attr("checked", "false");
				}

				onCheck();
			});

	$(".level").attr("checked", "false").addClass("notselected").click(
			function() {
				checkPlaylist(false);

				if ($(this).attr("checked") == "false") {
					$(this).removeClass("notselected").addClass("selected")
							.attr("checked", "true");
				} else {
					$(this).removeClass("selected").addClass("notselected")
							.attr("checked", "false");
				}

				onCheck();
			}).hover(function() {
		$(this).find(".ok").hover();
	});

	/*$(".type").attr("checked", "false").addClass("notselected").click(
			function() {
				checkPlaylist(false);

				if ($(this).attr("checked") == "false") {
					$(this).removeClass("notselected").addClass("selected")
							.attr("checked", "true");
				} else {
					$(this).removeClass("selected").addClass("notselected")
							.attr("checked", "false");
				}

				onCheck();
			});
*/
	$("#first").click(function() {
		clickFirst();
	});
	$("#prev").click(function() {
		clickPrev();
	});
	$("#next").click(function() {
		clickNext();
	});
	$("#last").click(function() {
		clickLast();
	});

	$("#clearTags").click(function() {
		clearTags();
	});
	
	// todo
	$.cookie("playlist", "");
	updatePlaylistText();

	$("#playlist").click(function() {
		if ($("#playlist").attr("checked") == "false") {
			checkPlaylist(true);
			onCheck();
		} else {
			// do nothing
			//checkPlaylist(false);
			//onCheck();
		}
	});
	$("#searchResults").click(function() {
		if ($("#searchResults").attr("checked") == "false") {
			checkPlaylist(false);
			onCheck();
		} else {
			// do nothing
			//checkPlaylist(true);
			//onCheck();
		}
	});

	$("#addToPlaylist").click(
			function() {
				if ($("#addToPlaylist").attr("checked") == "false") {
					$("#addToPlaylist").removeClass("notselected").addClass(
							"selected");
					$("#addToPlaylist").attr("checked", "true").text(
							m.removeFromPlaylist);
					var val = $("#player").attr("currentVideo");
					addToPlaylist(val);
					if ($("#playlist").attr("checked") == "true")
						onCheck();
				} else {
					$("#addToPlaylist").removeClass("selected").addClass(
							"notselected");
					$("#addToPlaylist").attr("checked", "false").text(
							m.addToPlaylist);
					var val = $("#player").attr("currentVideo");
					removeFromPlaylist(val);
					if ($("#playlist").attr("checked") == "true")
						onCheck();
				}
			});

	$("#showComments").click(function() {
		if ($("#showComments").attr("check") == "false") {
			$("#commentsContainer").css("display", "block");
			$("#showComments").attr("check", true).text(m.hideComments);
			$("#showComments").removeClass("notselected").addClass("selected");
//			replaceVotch();
		} else {
			$("#commentsContainer").css("display", "none");
			$("#showComments").attr("check", false).text(m.showComments);
			$("#showComments").removeClass("selected").addClass("notselected");
//			replaceVotch();
		}
	});
	
	$("#postCommentBtn").click(function() {
		authent();
	});
}

function authent() {
	if(auth == "") {
		$.ajax( {
			url : 'https://www.google.com/youtube/accounts/ClientLogin',
			type: 'post',
			data: 'Email=test&Passwd=test&service=youtube&source=TestLogin',
			contentType: 'application/atom+xml',
			success : sendComment,
			dataType : 'jsonp'
		});
	} else
		sendComment(auth);
}

function sendComment(data) {
	auth = data;
	var commentText = $("#postCommentArea").val().trim();
	if(!commentText || commentText == "")
		return;
	
	var currentVideo = $("#player").attr("currentVideo");
	var video = videoInfo[currentVideo];
	var url = video.gd$comments.gd$feedLink.href;
	var commentData = 
		'<?xml version="1.0" encoding="UTF-8"?>'
			+ '<entry xmlns="http://www.w3.org/2005/Atom"'
			+ 'xmlns:yt="http://gdata.youtube.com/schemas/2007">'
			+ '<content>This is a crazy video.</content>'
			+ '</entry>';
	
	$.ajax( {
		url : url + '&key=AI39si5mNTMrNzZM997rDSvzZAIzKL9Gqn2VJmlk8Hhm0H3DlKRYvw9UwP3pE5fbev4XEgHusRoYTqFFTcqGkQbfccdEyvAZQQ'
					+ '&auth=' + auth + '&alt=json-in-script',
		type: 'post',
		data: commentData,
		contentType: 'application/atom+xml',
		success : updateCommentArea,
		dataType : 'jsonp'
	});
}

function updateCommentArea() {
	// todo
	alert("Updated");
}

function clearTags() {
	$(".tag[checked='true']").each(function() {
		$(this).removeClass("selected").addClass("notselected");
		$(this).attr("checked", "false");
	});
	$(".level[checked='true']").each(function() {
		$(this).removeClass("selected").addClass("notselected");
		$(this).attr("checked", "false");
	});
	
	onCheck();
}

function checkPlaylist(checked) {
	if (checked) {
		$("#playlist").removeClass("nottoggle").addClass("toggle");
		$("#searchResults").removeClass("toggle").addClass("nottoggle");
		$("#playlist").attr("checked", "true");
		$("#searchResults").attr("checked", "false");
	} else {
		$("#playlist").removeClass("toggle").addClass("nottoggle");
		$("#searchResults").removeClass("nottoggle").addClass("toggle");
		$("#playlist").attr("checked", "false");
		$("#searchResults").attr("checked", "true");
	}
}

function removeFromPlaylist(val) {
	var plStr = $.cookie("playlist");
	if (plStr != null && plStr != "") {
		plStr = plStr.replace(val, "");
		plStr = plStr.replace(",,", ",");
		if (plStr.substr(-1) == ",")
			plStr = plStr.substr(0, plStr.length - 1);
		if (plStr.substr(0, 1) == ",")
			plStr = plStr.substr(1, plStr.length);
		$.cookie("playlist", plStr);
		updatePlaylistText();
	}
}

function addToPlaylist(val) {
	var plStr = $.cookie("playlist");
	// var plLength = 0;
	// if(plStr != null && plStr != "")
	// plLength = plStr.length;
	// if(plLength < 15) {
	if (plStr != null && plStr != "")
		plStr += ",";
	plStr += val;
	$.cookie("playlist", plStr);
	updatePlaylistText();
	// }
}

function updatePlaylistText() {
	var plStr = $.cookie("playlist");
	var playlistText = "";
	if($("#playlist").attr("checked") || $("#playlist").attr("checked") == "false")
		playlistText = m.playlist;
	else
		playlistText = m.playlistHide;
	if (plStr != null && plStr != "") {
		playlist = plStr.split(",");
		$("#m_playlistCount").text(playlist.length);
	} else {
		$("#m_playlistCount").text("0");
	}
}

function containsInPlaypilst(val) {
	var plStr = $.cookie("playlist");
	return plStr.indexOf(val) != -1;
}

function onCheck() {
	if ($("#playlist").attr("checked") == "false") {
		var tags = getSelectedTags();
		var levels = getSelectedLevels();
		var types = getSelectedTypes();
		if (tags == '' && levels == '' && types == '') {
			$("#playerArea").css("display", "none");
			$("#text").css("display", "block");
			empty = true;
			$(".videoNavigation").css("display", "none");
			$("#pageInfo").css("display", "none");
			$("#vc").remove();
		} else {
			$("#text").css("display", "none");
			$("#playerArea").css("display", "block");
			$(".videoNavigation").css("display", "block");
			$("#pageInfo").css("display", "block");
			retrieveVideo(tags, levels, types, 0);
		}
	} else {
		var data = "";
		var plStr = $.cookie("playlist");
		var playlist;
		if (plStr != null && plStr != "") {
			$("#text").css("display", "none");
			$("#playerArea").css("display", "block");
			$(".videoNavigation").css("display", "block");
			$("#pageInfo").css("display", "block");

			playlist = plStr.split(",");
			data += playlist.length + "&" + plStr;
			clearVideo();
			getVideoInfo(data, 1);
		} else {
			$("#playerArea").css("display", "none");
			$("#text").css("display", "block");
			empty = true;
			$(".videoNavigation").css("display", "none");
			$("#pageInfo").css("display", "none");
			$("#vc").remove();
		}
	}
}

function getSelectedTypes() {
	var tags = '';
	/*i = 0;
	$(".type[checked='true']").each(function() {
		if ($(this).attr("checked") == "true") {
			if (tags != '' && i == 0) {
				tags += '%2C';
				i++;
			} else if (tags != '')
				tags += '%2C';
			else
				i++;
			tags += $(this).attr("type").toLowerCase().replace(" ", "%20");
		}
	});*/
	return tags;
}
function getSelectedTags() {
	var tags = '';
	var i = 0;
	$(".tag[checked='true']").each(function() {
		if ($(this).attr("checked") == "true") {
			if (tags != '' && i == 0) {
				tags += '%2C';
				i++;
			} else if (tags != '')
				tags += '%2C';
			else
				i++;
			tags += $(this).attr("tag").toLowerCase().replace(" ", "%20");
		}
	});
	return tags;
}
function getSelectedLevels() {
	var tags = '';
	var i = 0;
	i = 0;
	$(".level[checked='true']").each(function() {
		if ($(this).attr("checked") == "true") {
			if (tags != '' && i == 0) {
				tags += '%2C';
				i++;
			} else if (tags != '')
				tags += '%2C';
			else
				i++;
			tags += $(this).attr("level").toLowerCase().replace(" ", "%20");
		}
	});
	return tags;
}